import * as echarts from 'echarts/core'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必要的组件
echarts.use([
  LineChart,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  CanvasRenderer
])

/**
 * 初始化echarts实例
 * @param {HTMLElement} el - DOM元素
 * @param {Object} options - 图表配置项
 * @returns {echarts.ECharts} - echarts实例
 */
export function initChart(el, options) {
  if (!el) return null
  const chart = echarts.init(el)
  options && chart.setOption(options)
  return chart
}

/**
 * 生成折线图配置
 * @param {Object} params - 图表参数
 * @returns {Object} - echarts配置项
 */
export function getLineChartOption(params = {}) {
  const { title, xData, series, legend } = params
  return {
    title: {
      text: title || '',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: legend || [],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xData || []
    },
    yAxis: {
      type: 'value'
    },
    series: series || []
  }
}

/**
 * 生成柱状图配置
 * @param {Object} params - 图表参数
 * @returns {Object} - echarts配置项
 */
export function getBarChartOption(params = {}) {
  const { title, xData, series, legend } = params
  return {
    title: {
      text: title || '',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: legend || [],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xData || []
    },
    yAxis: {
      type: 'value'
    },
    series: series || []
  }
}

/**
 * 生成饼图配置
 * @param {Object} params - 图表参数
 * @returns {Object} - echarts配置项
 */
export function getPieChartOption(params = {}) {
  const { title, series } = params
  return {
    title: {
      text: title || '',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0
    },
    series: [
      {
        name: series?.name || '',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: series?.data || []
      }
    ]
  }
}

export default echarts 